import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import * as path from 'path'
import { wrapperEnv } from './build/until'
//createVitePlugins是所有打包的Plugin 对象
import { createVitePlugins } from './build/vite/plugin'
import { createProxy } from './build/vite/proxy'
import { OUTPUT_DIR } from './build/vite/constant'

// 方法将路径或路径片段的序列解析为绝对路径。
function pathResolve(dirPath: string) {
  return path.resolve(__dirname, dirPath)
}

const alias: Record<string, string> = {
  '@': pathResolve('src'),
  '#': pathResolve('src/types'),
  path: "path-browserify"
}

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  // command: 你输入的命令
  // mode: 当前构建的环境

  const root = process.cwd() // 返回当前工作目录

  const isBuild = command === 'build'

  const env = loadEnv(mode, process.cwd()) // 检查当前路径下 env文件

  const viteEnv: any = wrapperEnv(env)

  const { VITE_PUBLIC_PATH, VITE_PROXY, VITE_PORT } = viteEnv

  return {
    resolve: {
      alias,
    },
    base: VITE_PUBLIC_PATH || './', // 打包路径
    plugins: createVitePlugins(viteEnv, isBuild),
    server: {
      port: VITE_PORT, // 服务端口号
      open: true, // 服务启动时是否自动打开浏览器
      cors: true, // 允许跨域
      proxy: createProxy(VITE_PROXY)
    },
    css: {
      // css预处理器
      preprocessorOptions: {
        scss: {
          charset: false,
          additionalData: '@import "./src/styles/_variables.scss";@import "./src/styles/_mixins.scss";'
        },
      },
    },
    build: {
      outDir: OUTPUT_DIR, //打包名称
      assetsDir: "assets", //指定静态资源存放路径
      sourcemap: false, //是否构建source map 文件
      terserOptions: {
        // 生产环境移除console
        compress: {
          drop_console: true,
          drop_debugger: true,
        }
      }
    }
  }
})
